<template>
  <div class="common-layout">
    <el-container>
      <el-aside width="200px">
        <el-input
          v-model="filterText"
          class="w-60 mb-2"
          placeholder="请输入医院"
        />

        <el-tree
          ref="treeRef"
          style="max-width: 600px"
          class="filter-tree"
          :data="data"
          :props="defaultProps"
          default-expand-all
          :filter-node-method="filterNode"
          highlight-current
          node-key="teamID"
          @node-click="handleNodeClick"
        />
      </el-aside>
      <el-container>
        <el-header>
          <el-form :inline="true" :model="form" class="demo-form-inline">
            <el-form-item label="机构名称">
              <el-input
                v-model="form.InstitutionName"
                placeholder="请输入机构名称"
                clearable
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="getTeamInfo()">查询</el-button>
            </el-form-item>
          </el-form>
        </el-header>
        <el-main>
          <el-button
            style="background-color: yellowgreen"
            plain
            @click="openDialog"
            >添加</el-button
          >

          <!-- 添加弹出框 -->
          <el-dialog
            v-model="dialogFormVisible"
            title="新增上转机构"
            width="800px"
          >
            <div>
              <el-row>
                <el-col :span="10">
                  <h4>待选列表</h4>
                  <el-table
                    :data="unselectedList"
                    style="width: 100%"
                    @selection-change="handleUnselectedSelectionChange"
                  >
                    <el-table-column type="selection" width="55" />
                    <el-table-column prop="institutionName" label="机构名称" />
                    <el-table-column prop="institutionType" label="机构类型" />
                    <el-table-column prop="address" label="地址" />
                  </el-table>
                </el-col>
                <el-col :span="4">
                  <div
                    style="
                      display: flex;
                      flex-direction: column;
                      justify-content: center;
                      align-items: center;
                    "
                  >
                    <el-button @click="moveToSelected">></el-button>
                    <el-button @click="moveToUnselected"><</el-button>
                  </div>
                </el-col>
                <el-col :span="10">
                  <h4>已选列表</h4>
                  <el-table
                    :data="selectedList"
                    style="width: 100%"
                    @selection-change="handleSelectedSelectionChange"
                  >
                    <el-table-column type="selection" width="55" />
                    <el-table-column prop="institutionName" label="机构名称" />
                    <el-table-column prop="institutionType" label="机构类型" />
                    <el-table-column prop="address" label="地址" />
                  </el-table>
                </el-col>
              </el-row>
              <div style="text-align: right; margin-top: 20px">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="success" @click="save">保存</el-button>
              </div>
            </div>
          </el-dialog>

          <!-- 团队管理列表 -->
          <el-table :data="tableData" style="width: 100%">
            <el-table-column
              prop="institutionName"
              label="机构名称"
              width="150"
            />
            <el-table-column
              prop="institutionType"
              label="机构类型"
              width="120"
            />
            <el-table-column prop="address" label="地址" width="120" />
            <el-table-column fixed="right" label="操作" min-width="120">
              <template v-slot="scope">
                <el-button
                  style="background-color: red"
                  plain
                  @click="DelTeamInfo(scope.row.institutionId)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import { onMounted, reactive, ref, watch } from "vue";
import type { TreeInstance } from "element-plus";
const apiUrl = import.meta.env.VITE_APP_API_URL;
interface Institution {
  institutionId: number;
  institutionName: string;
  institutionType: string;
  address: string;
}
// 静态测试数据
const staticInstitutions: Institution[] = [
  {
    institutionId: 1,
    institutionName: "默认医院一",
    institutionType: "综合医院",
    address: "北京市朝阳区示范路1号"
  },
  {
    institutionId: 2,
    institutionName: "默认医院二",
    institutionType: "专科医院",
    address: "北京市朝阳区测试路2号"
  }
];
const filterText = ref("");
const treeRef = ref<TreeInstance>();
const currentTeamId = ref<number>(0);
const dialogFormVisible = ref(false);
const unselectedList = ref<Institution[]>([]);
const selectedList = ref<Institution[]>([]);
const selectedUnselectedRows = ref<Institution[]>([]);
const selectedSelectedRows = ref<Institution[]>([]);

const form = reactive({
  InstitutionName: "",
});

const tableData = ref<Institution[]>([]);

// 加载机构数据
const getTeamInfo = async () => {
  try {
    const res = await axios.get(
      apiUrl+'/T7/BasicSettings/GetInstitution',
      { params: { InstitutionName: form.InstitutionName } }
    );
    // 仅显示接口数据，静态数据只在待选列表显示
    tableData.value = res.data.data;
    
  } catch (error) {
    ElMessage.error("获取机构数据失败");
    tableData.value = []; // 清空已选列表
  }
};

// 加载对话框数据
const loadDialogData = async () => {
  try {
    const res = await axios.get(apiUrl+'/T7/BasicSettings/GetInstitution');
    const apiData: Institution[] = res.data.data || [];
    
    // 合并接口数据和静态数据（去重）
    const allInstitutions = [
      ...apiData,
      ...staticInstitutions.filter(
        staticItem => !apiData.some(apiItem => apiItem.institutionId === staticItem.institutionId)
      )
    ];

    const selectedIds = tableData.value.map(item => item.institutionId);
    unselectedList.value = allInstitutions.filter(
      item => !selectedIds.includes(item.institutionId)
    );
    
    selectedList.value = tableData.value;
    selectedList.value = [];
  } catch (error) {
    const selectedIds = tableData.value.map(item => item.institutionId);
    unselectedList.value = staticInstitutions.filter(
      item => !selectedIds.includes(item.institutionId)
    );
    selectedList.value = tableData.value;
  }
};

const openDialog = async () => {
  dialogFormVisible.value = true;
  await loadDialogData();
};

// 处理树节点点击
const handleNodeClick = (nodeData: any) => {
  currentTeamId.value = nodeData.teamID;
};

// 列表移动处理
const handleUnselectedSelectionChange = (rows: Institution[]) => {
  selectedUnselectedRows.value = rows;
};

const handleSelectedSelectionChange = (rows: Institution[]) => {
  selectedSelectedRows.value = rows;
};

const moveToSelected = () => {
  selectedList.value.push(...selectedUnselectedRows.value);
  unselectedList.value = unselectedList.value.filter(
    (item) => !selectedUnselectedRows.value.includes(item)
  );
  selectedUnselectedRows.value = [];
};

const moveToUnselected = () => {
  unselectedList.value.push(...selectedSelectedRows.value);
  selectedList.value = selectedList.value.filter(
    (item) => !selectedSelectedRows.value.includes(item)
  );
  selectedSelectedRows.value = [];
};

// 保存处理
const save = async () => {
  try {
    await Promise.all(
      selectedList.value.map(async (item) => {
        const response = await axios.post(
          apiUrl+'/T7/BasicSettings/AddInstitution',
          {
            institutionName: item.institutionName,
            institutionType: item.institutionType,
            address: item.address,
          }
        );
        if (response.data.code !== 212) {
          throw new Error(response.data.msg);
        }
      })
    );
    ElMessage.success("添加成功");
    dialogFormVisible.value = false;
    // 将已选列表设为空
    selectedList.value = [];
     getTeamInfo();
  } catch (error) {
    ElMessage.error(error.message || "添加失败");
  }
};

// 删除处理
const DelTeamInfo = async (id: number) => {
  try {
    await ElMessageBox.confirm("确认删除这条数据吗？", "警告", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    });
    const res = await axios.delete(
      apiUrl+'/T8/BasicSettings/DelInstitution?InstitutionId=' + id,
     {data:{InstitutionId:id}}
    );
    if (res.data.code === 204) {
      ElMessage.success("删除成功");
       getTeamInfo();
    }
  } catch (error) {
    ElMessage.info("已取消删除");
  }
};

// 树形控件相关
interface Tree {
  [key: string]: any;
}

const data = ref<Tree[]>([]);
const defaultProps = {
  children: "children",
  label: "orgName",
};

const fetchTreeData = async () => {
  try {
    const res = await axios.get(
     apiUrl+'/T7/BasicSettings/GetTeamTree'
    );
    data.value = res.data.data.map((node: any) => ({
      ...node,
      label: node.orgName,
      children: node.children || [],
    }));
  } catch (error) {
    ElMessage.error("获取组织树失败");
  }
};

watch(filterText, (val) => {
  treeRef.value!.filter(val);
});

const filterNode = (value: string, data: Tree) => {
  if (!value) return true;
  return data.orgName.includes(value);
};

// 初始化
onMounted(() => {
  fetchTreeData();
  getTeamInfo();
});
</script>

<style scoped>
/* 添加必要的样式 */
</style>